<template>
  <div class="shares-container">
    <!-- 顶部统计 -->
    <div class="share-stats">
      <div class="stat-item">
        <LinkOutlined class="stat-icon active" />
        <div class="stat-info">
          <div class="stat-label">活跃分享</div>
          <div class="stat-value">{{ activeCount }}</div>
        </div>
      </div>
      <div class="stat-item">
        <ClockCircleOutlined class="stat-icon expired" />
        <div class="stat-info">
          <div class="stat-label">已过期</div>
          <div class="stat-value">{{ expiredCount }}</div>
        </div>
      </div>
      <div class="stat-item">
        <EyeOutlined class="stat-icon views" />
        <div class="stat-info">
          <div class="stat-label">总访问</div>
          <div class="stat-value">{{ totalShowCount }}</div>
        </div>
      </div>
    </div>

    <!-- 操作栏 -->
    <div class="operation-bar">
      <a-space>
        <a-button type="primary" @click="handleRefresh" :loading="loading">
          <template #icon><ReloadOutlined /></template>
          刷新
        </a-button>
        <a-popconfirm
          title="确定要取消这些分享吗？"
          @confirm="handleBatchDelete"
          placement="bottom"
          cancelText="取消"
          okText="确定"
        >
          <a-button type="primary" danger :disabled="selectedRowKeys.length === 0">
            <template #icon><DeleteOutlined /></template>
            批量取消
          </a-button>
        </a-popconfirm>
        <a-input-search
          v-model:value="searchParams.keyword"
          placeholder="搜索分享文件..."
          style="width: 220px"
          @search="handleSearch"
        />
      </a-space>
    </div>

    <!-- 分享列表 -->
    <div class="share-table">
      <a-table
        :columns="columns"
        :data-source="shareList"
        :pagination="{
          total: Number(shareTotal),
          current: Number(searchParams.pageNo),
          pageSize: Number(searchParams.pageSize),
          onChange: handlePageChange,
          showSizeChanger: true,
          showQuickJumper: true,
          size: 'small',
          showTotal: total => `共 ${total} 条`,
        }"
        :loading="loading"
        :row-selection="{
          selectedRowKeys: selectedRowKeys,
          onChange: onSelectChange,
          selections: [Table.SELECTION_ALL, Table.SELECTION_INVERT, Table.SELECTION_NONE],
        }"
        rowKey="shareId"
        size="small"
      >
        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'fileName'">
            <div class="file-cell">
              <div
                class="file-icon"
                :class="{
                  'has-cover': record.fileCover && (record.fileType === 1 || record.fileType === 3),
                }"
              >
                <!-- 图片和视频文件使用缩略图 -->
                <template v-if="record.fileType === 3 && record.fileCover">
                  <img :src="record.fileCover" :alt="record.fileName" />
                </template>
                <template v-else-if="record.fileType === 1 && record.fileCover">
                  <img :src="record.fileCover" :alt="record.fileName" />
                  <div class="video-overlay">
                    <i class="video-play-icon"></i>
                  </div>
                </template>
                <!-- 其他文件使用主题化图标 -->
                <template v-else>
                  <ThemeFileIcon 
                    :fileType="getFileTypeForIcon(record)" 
                    :fileName="record.fileName"
                    size="medium"
                  />
                </template>
              </div>
              <span class="file-name" :title="record.fileName">{{ record.fileName }}</span>
            </div>
          </template>
          <template v-if="column.key === 'fileSize'">
            <span>{{ formatFileSize(record.fileSize) }}</span>
          </template>
          <template v-if="column.key === 'code'">
            <a-space>
              <span class="share-code">{{ maskShareCode(record.code) }}</span>
              <a-button type="link" size="small" @click="handleCopyCode(record)">
                <template #icon><CopyOutlined style="color: #1890ff" /></template>
              </a-button>
            </a-space>
          </template>
          <template v-if="column.key === 'showCount'">
            <span>{{ record.showCount || 0 }}</span>
          </template>
          <template v-if="column.key === 'status'">
            <a-tag :color="record.expire ? 'error' : 'success'" size="small">
              {{ record.expire ? '已过期' : '有效' }}
            </a-tag>
          </template>
          <template v-if="column.key === 'action'">
            <a-space>
              <a-tooltip title="复制链接">
                <a-button type="link" size="small" @click="handleCopyLink(record)">
                  <template #icon><LinkOutlined style="color: #1890ff" /></template>
                </a-button>
              </a-tooltip>
              <a-tooltip title="取消分享">
                <a-popconfirm
                  title="确定要取消这个分享吗？"
                  @confirm="handleDelete(record)"
                  placement="left"
                  cancelText="取消"
                  okText="确定"
                >
                  <a-button type="link" size="small">
                    <template #icon><StopOutlined style="color: #ff4d4f" /></template>
                  </a-button>
                </a-popconfirm>
              </a-tooltip>
            </a-space>
          </template>
        </template>
      </a-table>
    </div>

    <!-- 编辑分享弹窗 -->
    <a-modal
      v-model:visible="editVisible"
      title="编辑分享"
      @ok="handleEditSubmit"
      :confirmLoading="editLoading"
      width="500px"
    >
      <a-form :model="editForm" layout="vertical">
        <a-form-item label="过期时间">
          <a-date-picker
            v-model:value="editForm.expireTime"
            show-time
            format="YYYY-MM-DD HH:mm:ss"
            style="width: 100%"
          />
        </a-form-item>
        <a-form-item label="访问密码">
          <a-input-password
            v-model:value="editForm.code"
            placeholder="留空表示无需密码"
            allow-clear
          />
        </a-form-item>
      </a-form>
    </a-modal>

    <!-- 分享详情抽屉 -->
    <a-drawer v-model:visible="detailsVisible" title="分享详情" placement="right" width="400">
      <template v-if="currentShare">
        <div class="share-details">
          <div class="detail-item">
            <div class="detail-label">文件名</div>
            <div class="detail-value">{{ currentShare.fileName }}</div>
          </div>
          <div class="detail-item">
            <div class="detail-label">分享链接</div>
            <div class="detail-value url">
              {{ currentShare.shareUrl }}
              <a-button type="link" @click="handleCopyLink(currentShare)">
                <CopyOutlined />
              </a-button>
            </div>
          </div>
          <div class="detail-item">
            <div class="detail-label">分享时间</div>
            <div class="detail-value">{{ formatDate(currentShare.shareTime) }}</div>
          </div>
          <div class="detail-item">
            <div class="detail-label">过期时间</div>
            <div class="detail-value">{{ formatDate(currentShare.expireTime) }}</div>
          </div>
          <div class="detail-item">
            <div class="detail-label">访问密码</div>
            <div class="detail-value">{{ currentShare.code || '无' }}</div>
          </div>
          <div class="detail-item">
            <div class="detail-label">状态</div>
            <div class="detail-value">
              <a-tag :color="currentShare.status === 'active' ? 'success' : 'error'">
                {{ currentShare.status === 'active' ? '有效' : '已过期' }}
              </a-tag>
            </div>
          </div>
        </div>
      </template>
    </a-drawer>
  </div>
</template>

<script setup lang="ts">
  import { ref, reactive, onMounted, computed } from 'vue'
  import { message, Table } from 'ant-design-vue'
  import {
    ReloadOutlined,
    DeleteOutlined,
    LinkOutlined,
    ClockCircleOutlined,
    CopyOutlined,
    EyeOutlined,
    StopOutlined,
  } from '@ant-design/icons-vue'
  import { formatDate } from '@/utils/date'
  import { loadShareListUsingPost, cancelShareUsingPost } from '@/api/wenjiangongxiangjiekou'
  import ThemeFileIcon from '@/components/ThemeFileIcon.vue'

  // 导入图标
  import folderIcon from '@/assets/files/文件夹.png'
  import imageIcon from '@/assets/files/图片.png'
  import videoIcon from '@/assets/files/视频.png'
  import audioIcon from '@/assets/files/音乐.png'
  import pdfIcon from '@/assets/files/pdf.png'
  import docIcon from '@/assets/files/doc.png'
  import excelIcon from '@/assets/files/excel.png'
  import txtIcon from '@/assets/files/txt.png'
  import codeIcon from '@/assets/files/code.png'
  import zipIcon from '@/assets/files/zip.png'
  import otherIcon from '@/assets/files/其他.png'

  // 搜索参数
  const searchParams = reactive({
    pageNo: '1',
    pageSize: '10',
    keyword: '',
  })

  // 列表数据
  const loading = ref(false)
  const shareTotal = ref('0')
  const shareList = ref([])

  // 统计数据计算
  const activeCount = computed(() => shareList.value.filter(item => !item.expire).length)
  const expiredCount = computed(() => shareList.value.filter(item => item.expire).length)
  const totalShowCount = computed(() =>
    shareList.value.reduce((sum, item) => sum + (item.showCount || 0), 0)
  )

  // 表格列定义
  const columns = [
    {
      title: '文件名',
      dataIndex: 'fileName',
      key: 'fileName',
      width: '25%',
      ellipsis: true,
    },
    {
      title: '大小',
      dataIndex: 'fileSize',
      key: 'fileSize',
      width: '10%',
    },
    {
      title: '分享码',
      dataIndex: 'code',
      key: 'code',
      width: '15%',
    },
    {
      title: '访问次数',
      dataIndex: 'showCount',
      key: 'showCount',
      width: '10%',
    },
    {
      title: '过期时间',
      dataIndex: 'expireTime',
      key: 'expireTime',
      width: '15%',
      customRender: ({ text }) => formatDate(text),
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      width: '10%',
    },
    {
      title: '操作',
      key: 'action',
      width: '15%',
      align: 'center',
    },
  ]

  // 获取分享列表
  const fetchShareList = async () => {
    loading.value = true
    try {
      const res = await loadShareListUsingPost(searchParams)
      if (res.data?.code === 200) {
        shareList.value = res.data.data.list || []
        shareTotal.value = res.data.data.totalCount || '0'
      } else {
        message.error(res.data?.message || '获取分享列表失败')
      }
    } catch {
      message.error('获取分享列表失败')
    } finally {
      loading.value = false
    }
  }

  // 页码变化处理
  const handlePageChange = (page: number, pageSize?: number) => {
    searchParams.pageNo = page.toString()
    if (pageSize) {
      searchParams.pageSize = pageSize.toString()
    }
    fetchShareList()
  }

  // 搜索处理
  const handleSearch = () => {
    searchParams.pageNo = '1'
    fetchShareList()
  }

  // 刷新处理
  const handleRefresh = () => {
    searchParams.keyword = ''
    fetchShareList()
  }

  // 复制文本的通用方法
  const copyText = (text: string) => {
    // 首先尝试使用 Clipboard API
    if (navigator.clipboard && window.isSecureContext) {
      navigator.clipboard
        .writeText(text)
        .then(() => {
          message.success('复制成功')
        })
        .catch(() => {
          // 如果 Clipboard API 失败，使用传统方法
          fallbackCopyText(text)
        })
    } else {
      // 在非安全上下文中使用传统方法
      fallbackCopyText(text)
    }
  }

  // 传统的复制方法
  const fallbackCopyText = (text: string) => {
    try {
      const input = document.createElement('input')
      input.style.position = 'fixed'
      input.style.opacity = '0'
      input.value = text
      document.body.appendChild(input)
      input.select()
      input.setSelectionRange(0, 99999)
      document.execCommand('copy')
      document.body.removeChild(input)
      message.success('复制成功')
    } catch (err) {
      console.error('复制失败:', err)
      message.error('复制失败')
    }
  }

  // 复制分享码
  const handleCopyCode = (record: any) => {
    copyText(record.code)
  }

  // 复制链接
  const handleCopyLink = (record: any) => {
    const shareLink = `${window.location.origin}/s/${record.shareId}`
    copyText(shareLink)
  }

  // 查看详情
  const detailsVisible = ref(false)
  const currentShare = ref<any>(null)

  // 编辑相关
  const editVisible = ref(false)
  const editLoading = ref(false)
  const editForm = reactive({
    expireTime: null,
    code: '',
  })

  const handleEditSubmit = async () => {
    if (!currentShare.value) return

    editLoading.value = true
    try {
      // TODO: 实现编辑分享的API调用
      message.success('编辑成功')
      editVisible.value = false
      fetchShareList()
    } catch {
      message.error('编辑失败')
    } finally {
      editLoading.value = false
    }
  }

  // 删除处理
  const handleDelete = async (record: any) => {
    try {
      const res = await cancelShareUsingPost({
        shareIds: record.shareId,
      })
      if (res.data?.code === 200) {
        message.success('删除成功')
        fetchShareList()
      } else {
        message.error(res.data?.message || '删除失败')
      }
    } catch {
      message.error('删除失败')
    }
  }

  // 获取文件类型用于ThemeFileIcon
  const getFileTypeForIcon = (record: any) => {
    if (record.folderType === 1) return 'folder'
    
    const fileName = record.fileName || ''
    const ext = fileName.split('.').pop()?.toLowerCase()
    
    // 根据文件扩展名判断类型
    if (['mp4', 'avi', 'mov', 'wmv', 'flv'].includes(ext)) return 'video'
    if (['mp3', 'wav', 'ogg', 'flac'].includes(ext)) return 'audio'
    if (['jpg', 'jpeg', 'png', 'gif', 'bmp', 'webp'].includes(ext)) return 'image'
    if (ext === 'pdf') return 'pdf'
    if (['doc', 'docx'].includes(ext)) return 'document'
    if (['xls', 'xlsx'].includes(ext)) return 'document'
    if (['txt', 'log', 'md'].includes(ext)) return 'document'
    if (['js', 'ts', 'java', 'py', 'cpp', 'c', 'php', 'html', 'css'].includes(ext)) return 'code'
    if (['zip', 'rar', '7z', 'tar', 'gz'].includes(ext)) return 'archive'
    
    return 'default'
  }

  // 掩码分享码
  const maskShareCode = (code: string) => {
    if (!code) return ''
    if (code.length <= 4) return code
    return code.substring(0, 4) + '****'
  }

  // 格式化文件大小
  const formatFileSize = (size: string) => {
    const num = parseInt(size)
    if (num < 1024) {
      return num + ' B'
    } else if (num < 1024 * 1024) {
      return (num / 1024).toFixed(1) + ' KB'
    } else if (num < 1024 * 1024 * 1024) {
      return (num / (1024 * 1024)).toFixed(1) + ' MB'
    } else {
      return (num / (1024 * 1024 * 1024)).toFixed(1) + ' GB'
    }
  }

  // 选中的行
  const selectedRowKeys = ref<string[]>([])

  // 选择改变事件
  const onSelectChange = (keys: string[]) => {
    selectedRowKeys.value = keys
  }

  // 批量删除
  const handleBatchDelete = async () => {
    if (selectedRowKeys.value.length === 0) {
      return
    }

    try {
      const shareIds = selectedRowKeys.value.join(',')
      await cancelShareUsingPost({ shareIds })
      message.success('批量取消分享成功')
      selectedRowKeys.value = []
      handleRefresh()
    } catch {
      message.error('批量取消分享失败')
    }
  }

  // 初始化
  onMounted(() => {
    fetchShareList()
  })
</script>

<style scoped>
  .shares-container {
    padding: 12px;
    background: var(--theme-surface);
    min-height: calc(100vh - 64px);
    transition: all 0.3s ease;
  }

  .share-stats {
    display: flex;
    gap: 16px;
    margin-bottom: 16px;
    padding: 16px;
    background: var(--theme-background);
    border-radius: 4px;
    transition: all 0.3s ease;
  }

  .stat-item {
    display: flex;
    align-items: center;
    gap: 8px;
    padding: 8px 16px;
    background: var(--theme-surface);
    border-radius: 4px;
    box-shadow: 0 1px 2px var(--theme-shadow);
    min-width: 160px;
    transition: all 0.3s ease;
  }

  .stat-icon {
    font-size: 24px;
    padding: 8px;
    border-radius: 8px;
    background: #f0f0f0;
  }

  .stat-icon.active {
    color: #52c41a;
    background: #f6ffed;
  }

  .stat-icon.expired {
    color: #ff4d4f;
    background: #fff1f0;
  }

  .stat-icon.views {
    color: #1890ff;
    background: #e6f7ff;
  }

  .stat-info {
    display: flex;
    flex-direction: column;
  }

  .stat-label {
    font-size: 13px;
    color: var(--theme-textSecondary);
    transition: color 0.3s ease;
  }

  .stat-value {
    font-size: 20px;
    font-weight: 600;
    color: var(--theme-text);
    transition: color 0.3s ease;
  }

  .operation-bar {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 16px;
    padding: 8px 16px;
    background: var(--theme-background);
    border-radius: 4px;
    transition: all 0.3s ease;
  }

  .share-table {
    background: var(--theme-surface);
    transition: all 0.3s ease;
  }

  .file-cell {
    display: flex;
    align-items: center;
    gap: 8px;
  }

  .file-icon {
    width: 32px;
    height: 32px;
    border-radius: 4px;
    overflow: hidden;
    display: flex;
    align-items: center;
    justify-content: center;
    background: #f5f7fa;
    position: relative;
  }

  .file-icon img {
    width: 100%;
    height: 100%;
    object-fit: contain;
  }

  .file-icon.has-cover img {
    object-fit: cover;
  }

  .video-overlay {
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background: rgba(0, 0, 0, 0.3);
    display: flex;
    align-items: center;
    justify-content: center;
  }

  .video-play-icon {
    width: 0;
    height: 0;
    border-style: solid;
    border-width: 8px 0 8px 12px;
    border-color: transparent transparent transparent #ffffff;
  }

  .file-name {
    color: var(--theme-text);
    font-size: 13px;
    transition: color 0.3s ease;
  }

  .share-code {
    font-family: monospace;
    background: var(--theme-background);
    color: var(--theme-text);
    padding: 2px 6px;
    border-radius: 2px;
    font-size: 13px;
    transition: all 0.3s ease;
  }

  :deep(.ant-table) {
    font-size: 13px;
    background: var(--theme-surface);
    color: var(--theme-text);
  }

  :deep(.ant-table-thead > tr > th) {
    background: var(--theme-background);
    color: var(--theme-text);
    padding: 8px 16px;
    border-bottom: 1px solid var(--theme-border);
  }

  :deep(.ant-table-tbody > tr > td) {
    padding: 8px 16px;
    color: var(--theme-text);
    border-bottom: 1px solid var(--theme-border);
  }

  :deep(.ant-table-tbody > tr:hover > td) {
    background: var(--theme-background);
  }

  :deep(.ant-table-tbody > tr > td) {
    background: var(--theme-surface);
  }

  :deep(.ant-tag) {
    margin: 0;
  }

  :deep(.ant-btn-link) {
    padding: 0 4px;
    height: 24px;
  }
</style>
